package com.zxl.always.on.display.ui.adapter;

import android.content.Context;
import android.graphics.LinearGradient;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.zxl.always.on.display.R;
import com.zxl.always.on.display.model.PaletteSet;
import com.zxl.always.on.display.model.bean.PaletteItem;
import com.zxl.always.on.display.tools.GraphicUtils;

import java.util.List;

/**
 * Created by Administrator on 2018/3/2.
 */

public class ColorPaletteAdapter extends BaseAdapter {

    private Context mContext;

    private int mSelectPosition;

    private List<PaletteItem> mList;

    public ColorPaletteAdapter(Context mContext, int mSelectPosition) {
        this.mContext = mContext;
        this.mSelectPosition = mSelectPosition;
        mList = PaletteSet.getPaletteItems();
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public PaletteItem getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (null == convertView) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.widget_palette_view_item, parent, false);
        }
        PaletteItem paletteItem = getItem(position);
        convertView.findViewById(R.id.palette_item_selected_check).setVisibility(mSelectPosition == position ? View.VISIBLE : View.GONE);
        Drawable drawable = mContext.getResources().getDrawable(R.drawable.circle_solid);
        ImageView imageView = convertView.findViewById(R.id.palette_item_image);
        if (paletteItem.getType() == PaletteItem.Type.SOLID) {
            drawable.setColorFilter(new PorterDuffColorFilter(paletteItem.getColor(), PorterDuff.Mode.SRC_IN));
            imageView.setImageDrawable(drawable);
        } else {
            int height = mContext.getResources().getDimensionPixelOffset(R.dimen.palette_gridview_item_content_size);
            LinearGradient linearGradient = new LinearGradient(0, 0, 0, height, paletteItem.getColors(), paletteItem.getPositions(), Shader.TileMode.CLAMP);
            BitmapDrawable bitmapDrawable = GraphicUtils.getLinearGradientDrawable(mContext, drawable, height, height, -30, linearGradient);
            imageView.setImageDrawable(bitmapDrawable);
        }
        return convertView;
    }

    public void setSelectPosition(int position) {
        mSelectPosition = position;
        notifyDataSetChanged();
    }

    public int getSelectPosition() {
        return mSelectPosition;
    }
}
